{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-07-15T04:35:52.619785Z",
     "start_time": "2025-07-15T04:35:46.182328Z"
    }
   },
   "source": [
    "\n",
    "import os\n",
    "\n",
    "from langchain.chat_models import init_chat_model\n",
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "\n",
    "os.environ[\"DEEPSEEK_API_KEY\"] = \"sk-78d9495ae9e24bfeb48715356e1bd52e\"\n",
    "\n",
    "model = init_chat_model(\"deepseek-chat\", model_provider=\"deepseek\")\n",
    "# model.invoke([HumanMessage(content=\"你是什么模型\")])\n",
    "\n",
    "model.invoke(\n",
    "    [\n",
    "        HumanMessage(content=\"Hi! I'm Bob\"),\n",
    "        AIMessage(content=\"Hello Bob! How can I assist you today?\"),\n",
    "        HumanMessage(content=\"What's my name?\"),\n",
    "    ]\n",
    ")"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content=\"Your name is **Bob**—unless you're testing my memory, in which case... I passed! 😄 How can I help you, Bob?\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 31, 'prompt_tokens': 26, 'total_tokens': 57, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 26}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0623_fp8_kvcache', 'id': '4367e11c-bcce-456b-966f-29ee34df6178', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--35059343-1ac2-4256-8e8b-38d0f8c700ee-0', usage_metadata={'input_tokens': 26, 'output_tokens': 31, 'total_tokens': 57, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:12:04.192531Z",
     "start_time": "2025-07-15T05:12:03.609866Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.chat_models import init_chat_model\n",
    "\n",
    "# 初始化模型，指定 base_url 为 DashScope 的 OpenAI 兼容接口地址\n",
    "model = init_chat_model(\n",
    "    \"glm-4-flash-250414\",  # 可替换为你想使用的 DashScope 模型，如 qwen-plus、qwen-turbo 等\n",
    "    model_provider=\"openai\",\n",
    "    base_url=\"https://open.bigmodel.cn/api/paas/v4/\",\n",
    "    openai_api_key=\"f1083622e2424058bfb7cdf7e48a7fb4.XxRmRC4VFmbNjz0K\"\n",
    ")\n",
    "\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.graph import START, MessagesState, StateGraph\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(state_schema=MessagesState)\n",
    "\n",
    "\n",
    "# Define the function that calls the model\n",
    "def call_model(state: MessagesState):\n",
    "    response = model.invoke(state[\"messages\"])\n",
    "    return {\"messages\": response}\n",
    "\n",
    "\n",
    "# Define the (single) node in the graph\n",
    "workflow.add_edge(START, \"model\")\n",
    "workflow.add_node(\"model\", call_model)\n",
    "\n",
    "# Add memory\n",
    "memory = MemorySaver()\n",
    "app = workflow.compile(checkpointer=memory)\n",
    "\n",
    "config = {\"configurable\": {\"thread_id\": \"abc123\"}}\n",
    "query = \"Hi! I'm Bob.\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = app.invoke({\"messages\": input_messages}, config)\n",
    "output[\"messages\"][-1].pretty_print()  # output contains all messages in state"
   ],
   "id": "94b0c56cbd912ee8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "Hi Bob! How can I assist you today?\n"
     ]
    }
   ],
   "execution_count": 39
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:12:06.389437Z",
     "start_time": "2025-07-15T05:12:06.076203Z"
    }
   },
   "cell_type": "code",
   "source": [
    "query = \"What's my name?\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = app.invoke({\"messages\": input_messages}, config)\n",
    "output[\"messages\"][-1].pretty_print()"
   ],
   "id": "28c80d843a410d4d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "Your name is Bob.\n"
     ]
    }
   ],
   "execution_count": 40
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:15:58.937907Z",
     "start_time": "2025-07-15T05:15:58.933004Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "\n",
    "prompt_template = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You talk like a pirate. Answer all questions to the best of your ability.\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")"
   ],
   "id": "f1889a00b84314e2",
   "outputs": [],
   "execution_count": 42
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-15T05:16:39.633856Z",
     "start_time": "2025-07-15T05:16:38.751223Z"
    }
   },
   "cell_type": "code",
   "source": [
    "workflow = StateGraph(state_schema=MessagesState)\n",
    "\n",
    "\n",
    "def call_model(state: MessagesState):\n",
    "    prompt = prompt_template.invoke(state)\n",
    "    response = model.invoke(prompt)\n",
    "    return {\"messages\": response}\n",
    "\n",
    "\n",
    "workflow.add_edge(START, \"model\")\n",
    "workflow.add_node(\"model\", call_model)\n",
    "\n",
    "memory = MemorySaver()\n",
    "app = workflow.compile(checkpointer=memory)"
   ],
   "id": "b507e56d7d0831f0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001B[1m Ai Message \u001B[0m==================================\n",
      "\n",
      "Arrr, welcome aboard, Jim! What be yer quest today? Speak yer mind and I'll do me best to aid ye in this grand ocean of knowledge!\n"
     ]
    }
   ],
   "execution_count": 44
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"abc345\"}}\n",
    "query = \"Hi! I'm Jim.\"\n",
    "\n",
    "input_messages = [HumanMessage(query)]\n",
    "output = app.invoke({\"messages\": input_messages}, config)\n",
    "output[\"messages\"][-1].pretty_print()"
   ],
   "id": "427d42d8785ec4e9"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
